<template>
  <div class="prizes-container">
    <a-card>
      <template #title>奖品管理</template>
      <template #extra>
        <a-button type="primary" @click="handleAdd">
          <template #icon><PlusOutlined /></template>
          添加奖品
        </a-button>
      </template>

      <a-form layout="inline" class="search-form">
        <a-form-item label="奖品名称" class="search-form-item">
          <a-input
            v-model:value="searchForm.name"
            placeholder="请输入奖品名称"
            allow-clear
            @pressEnter="handleSearch"
            style="width: 200px"
          />
        </a-form-item>
        <a-form-item class="search-form-item">
          <a-button type="primary" @click="handleSearch">
            <template #icon><SearchOutlined /></template>
            搜索
          </a-button>
          <a-button style="margin-left: 8px" @click="handleReset">
            <template #icon><ReloadOutlined /></template>
            重置
          </a-button>
        </a-form-item>
      </a-form>

      <a-table
        :columns="columns"
        :data-source="prizes"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'image'">
            <a-image
              :src="getImageUrl(record.image)"
              :preview="{
                src: getImageUrl(record.image)
              }"
              style="width: 50px; height: 50px; object-fit: cover"
            />
          </template>
          <template v-if="column.key === 'value'">
            ¥{{ record.value }}
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="确定要删除该奖品吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDelete(record)"
              >
                <a class="danger-link">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <a-modal
      v-model:visible="dialogVisible"
      :title="dialogType === 'add' ? '添加奖品' : '编辑奖品'"
      @ok="handleDialogConfirm"
      :confirm-loading="dialogLoading"
      :maskClosable="false"
      width="600px"
    >
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        layout="horizontal"
      >
        <a-form-item label="奖品名称" name="name">
          <a-input v-model:value="form.name" placeholder="请输入奖品名称" />
        </a-form-item>
        <a-form-item label="奖品价值" name="value">
          <a-input-number
            v-model:value="form.value"
            placeholder="请输入奖品价值"
            :min="0"
            :precision="2"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="奖品数量" name="count">
          <a-input-number
            v-model:value="form.count"
            placeholder="请输入奖品数量"
            :min="0"
            :precision="0"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="奖品图片" name="image">
          <a-upload
            v-model:file-list="fileList"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :before-upload="beforeUpload"
            :show-upload-list="false"
            @change="handleUploadChange"
            accept="image/*"
          >
            <div class="upload-wrapper">
              <div v-if="form.image" class="image-preview">
                <img :src="getImageUrl(form.image)" alt="奖品图片" />
                <div class="image-actions">
                  <a-button type="link" @click.stop="handlePreview">预览</a-button>
                  <a-button type="link" @click.stop="handleRemoveImage">删除</a-button>
                </div>
              </div>
              <div v-else class="upload-trigger">
                <plus-outlined />
                <div style="margin-top: 8px">上传图片</div>
              </div>
            </div>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal
      v-model:visible="previewVisible"
      :footer="null"
      @cancel="handlePreviewCancel"
    >
      <img :src="previewImage" style="width: 100%" />
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, SearchOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import type { TablePaginationConfig } from 'ant-design-vue'
import type { UploadChangeParam, UploadProps } from 'ant-design-vue'
import { prizeApi } from '../api/prize'
import { getToken } from '../utils/auth'
import type { ApiResponse, PageResult } from '../types/api'

interface Prize {
  id: number
  name: string
  value: number
  image: string
  count: number
  createTime: string
  updateTime: string
}

interface SearchForm {
  name: string
}

interface Form {
  id?: number
  name: string
  value: number
  image: string
  count: number
}

const columns = [
  {
    title: '奖品名称',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '奖品图片',
    dataIndex: 'image',
    key: 'image',
    width: 100
  },
  {
    title: '奖品价值',
    dataIndex: 'value',
    key: 'value',
    width: 120
  },
  {
    title: '奖品数量',
    dataIndex: 'count',
    key: 'count',
    width: 120
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime'
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right'
  }
]

const prizes = ref<Prize[]>([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const dialogLoading = ref(false)
const formRef = ref()
const fileList = ref([])
const previewVisible = ref(false)
const previewImage = ref('')

// 使用 Vite 环境变量
const apiUrl = import.meta.env.VITE_API_URL
const staticUrl = import.meta.env.VITE_STATIC_URL
const uploadUrl = `${apiUrl}/api/lottery/file/upload`

const searchForm = reactive<SearchForm>({
  name: ''
})

const form = reactive<Form>({
  name: '',
  value: 0,
  image: '',
  count: 0
})

const rules = {
  name: [
    { required: true, message: '请输入奖品名称' }
  ],
  value: [
    { required: true, message: '请输入奖品价值' }
  ],
  count: [
    { required: true, message: '请输入奖品数量' }
  ],
  image: [
    { required: true, message: '请上传奖品图片' }
  ]
}

const pagination = reactive<TablePaginationConfig>({
  total: 0,
  current: 1,
  pageSize: 10,
  showSizeChanger: true,
  showTotal: (total) => `共 ${total} 条`
})

const uploadHeaders = {
  Authorization: `Bearer ${getToken()}`
}

const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('只能上传图片文件！')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB！')
    return false
  }
  return true
}

const handleUploadChange = (info: UploadChangeParam) => {
  if (info.file.status === 'done') {
    const response = info.file.response
    if (response) {
      form.image = response.data
      fileList.value = [{
        uid: info.file.uid,
        name: info.file.name,
        status: 'done',
        url: getImageUrl(response.data)
      }]
      message.success('上传成功')
    } else {
      message.error('上传失败')
    }
  } else if (info.file.status === 'error') {
    message.error('上传失败')
  }
}

const handlePreview = () => {
  previewImage.value = getImageUrl(form.image)
  previewVisible.value = true
}

const handlePreviewCancel = () => {
  previewVisible.value = false
}

const handleRemoveImage = () => {
  form.image = ''
  fileList.value = []
}

const getImageUrl = (image: string | { data: string } | null) => {
  if (!image) return ''
  
  console.log('Current image:', image)
  // 如果是相对路径，使用静态文件服务器地址
  // 处理新的响应格式，如果image是对象且包含data字段，则使用data字段的值
  const imagePath = typeof image === 'object' && image?.data ? image.data : image
  return `${staticUrl}${imagePath}`
}

const loadPrizes = async () => {
  loading.value = true
  try {
    const res = await prizeApi.getList({
      current: pagination.current || 1,
      size: pagination.pageSize || 10,
      name: searchForm.name
    })
    prizes.value = res.data.records
    pagination.total = res.data.total
  } catch (error) {
    message.error('获取奖品列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadPrizes()
}

const handleReset = () => {
  searchForm.name = ''
  pagination.current = 1
  loadPrizes()
}

const handleTableChange = (pag: TablePaginationConfig) => {
  if (pag.current) pagination.current = pag.current
  if (pag.pageSize) pagination.pageSize = pag.pageSize
  loadPrizes()
}

const resetForm = () => {
  form.id = undefined
  form.name = ''
  form.value = 0
  form.image = ''
  form.count = 0
  fileList.value = []
}

const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (record: Prize) => {
  dialogType.value = 'edit'
  form.id = record.id
  form.name = record.name
  form.value = record.value
  form.image = record.image
  form.count = record.count
  if (record.image) {
    fileList.value = [{
      uid: '-1',
      name: 'image.png',
      status: 'done',
      url: getImageUrl(record.image)
    }]
  }
  dialogVisible.value = true
}

const handleDelete = async (record: Prize) => {
  try {
    await prizeApi.delete(record.id)
    message.success('删除成功')
    loadPrizes()
  } catch (error) {
    message.error('删除失败')
  }
}

const handleDialogConfirm = async () => {
  try {
    await formRef.value.validate()
    dialogLoading.value = true
    
    if (dialogType.value === 'add') {
      await prizeApi.save(form)
      message.success('添加成功')
    } else {
      await prizeApi.update(form.id!, form)
      message.success('更新成功')
    }
    
    dialogVisible.value = false
    loadPrizes()
  } catch (error) {
    if (error instanceof Error) {
      message.error(error.message)
    }
  } finally {
    dialogLoading.value = false
  }
}

onMounted(() => {
  loadPrizes()
})
</script>

<style scoped>
.prizes-container {
  padding: 24px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.search-form {
  margin-bottom: 24px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
  width: 100%;
}

.search-form-item {
  margin-bottom: 16px;
  flex-shrink: 0;
}

.search-form-item:last-child {
  margin-left: 0;
  margin-bottom: 16px;
}

.danger-link {
  color: #ff4d4f;
}

.danger-link:hover {
  color: #ff7875;
}

.upload-wrapper {
  width: 128px;
  height: 128px;
  border: 1px dashed #d9d9d9;
  border-radius: 2px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.upload-wrapper:hover {
  border-color: #1890ff;
}

.upload-trigger {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
}

.image-preview {
  width: 100%;
  height: 100%;
  position: relative;
}

.image-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-actions {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.45);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-preview:hover .image-actions {
  opacity: 1;
}

:deep(.ant-form-item) {
  margin-bottom: 16px;
}

:deep(.ant-modal-body) {
  padding: 24px;
}

:deep(.ant-card) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.ant-card-body) {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

:deep(.ant-table-wrapper) {
  flex: 1;
  overflow: hidden;
}

:deep(.ant-table) {
  height: 100%;
}

:deep(.ant-table-container) {
  height: 100%;
}

:deep(.ant-table-body) {
  height: calc(100% - 39px) !important;
  overflow-y: auto !important;
}
</style> 